/**
 * @author:linjiye
 * @date: 2025/1/3
 * @desc:
 **/

import {StyleSheet, Text, TextInput, TouchableOpacity, View} from 'react-native'
import React, {useEffect, useState} from 'react'
import {aiOriginalityData} from "@/utils/data";
import {router} from "expo-router";
import {FcView} from "@/components/FcView";
import FormTitle from "@/components/FormTitle";
import {Flex} from "@ant-design/react-native";
import FcButton from "@/components/FcButton";
import FcSlider from "@/components/FcSlider";
import FcModal from "@/components/FcModal";
import NoData from "@/components/NoData";
import {
  useGetItemListQuery,
  useGetParentListQuery,
  useProfitModelInfoMutation
} from "@/store/api/aiOriginality/aiOriginalityApi";
import {useDispatch, useSelector} from "react-redux";
import {set_params} from "@/store/reducer/useExplosive/useExplosiveSlice";
import FcSearch from "@/components/FcSearch";

type Props = {}
const UseExplosiveWrap = (props: Props) => {
  const [typeList, setTypeList] = useState([
    {
      name: '提供产品',
      id: 1,
    }, {
      name: '提供服务',
      id: 12
    }
  ])
  const [typeId, setTypeId] = useState(typeList[0]?.id)
  const [productGroup, setProductGroup] = useState('全部')
  const [productName, setProductName] = useState('')
  const [productYL, setProductYL] = useState('')
  const [productGroupItem, setProductGroupItem] = useState({})
  const [productNameItem, setProductNameItem] = useState({})
  const [ylItem, setYlItem] = useState('')
  const [list, setList] = useState(aiOriginalityData)
  const [bigMenuId, setBigMenuId] = useState(list[0]?.id)
  const [smallMenu, setSmallMenu] = useState([])
  const [smallMenuId, setSmallMenuId] = useState(0)
  const [FcSliderZSVal, setFcSliderZSVal] = useState(100)
  const [FcSliderPSVal, setFcSliderPSVal] = useState(1)
  const [openProductGroup, setOpenProductGroup] = useState(false)
  const [openProduct, setOpenProduct] = useState(false)
  const [openProductYL, setOpenProductYL] = useState(false)
  const [groupList, setGroupList] = useState([])
  const [productList, setProductList] = useState([])
  const [ylList, setYlList] = useState([])
  const [pressedIndex, setPressedIndex] = useState(-1);

  const [groupSearchText, setGroupSearchText] = useState('')
  const [productSearchText, setProductSearchText] = useState('')

  const {data:groupResData,isSuccess:groupSuccess, refetch:groupRefetch}= useGetParentListQuery?.({
    type: typeId,
    name: groupSearchText
  })
  const {data:productResData,isSuccess:productSuccess, refetch:productRefetch}= useGetItemListQuery?.({
    parentId: productGroupItem?.id,
    name: productSearchText
  })
  const [profitModelInfoFun] = useProfitModelInfoMutation?.()

  const [params,setParams] = useState({})

  const dispatch = useDispatch()
  let p = useSelector(state => state.useExplosive.params)

  useEffect(() => {
    if(p) setParams(p)

    handleBigMenu(list[0])

    if (groupSuccess) {
      setGroupList(groupResData.result || [])
    }
    if (productSuccess) {
      setProductList(productResData.result || [])
    }


  },[groupSuccess,groupResData,productSuccess,productResData,p])

  const header = (
      <TouchableOpacity>
        <View style={styles.search_wrap}>
          <Text style={{fontFamily: 'FcIconFont',fontSize: 20,color: '#000000',marginRight: 7}}>&#xe641;</Text>
          <TextInput style={styles.search} placeholder={'请输入要搜索内容'} placeholderTextColor={'rgba(0, 0, 0, 0.3)'}/>
        </View>
      </TouchableOpacity>
  )


  const getProfitModelInfoFun = (id) => {
    profitModelInfoFun({
      id
    }).then(res => {
      if (res?.data?.code === 200) {
        setYlList(res?.data?.result || [])
      }
    })
  }

  const handleProduct = (val) => {
    setTypeId(val.id)
  }


  const handleBigMenu = (val) => {
    setBigMenuId(val.id)
    setSmallMenu(val.list)
    setSmallMenuId(val.list[0]?.id)
  }

  const handleSmallMenu = (val) => {
    setSmallMenuId(val.id)
  }

  const handleHotKeyword = () => {

  }

  const handleFcZSSlider = (val) => {
    setFcSliderZSVal(val)

    dispatch(set_params({
      ...params,
      wordsNum: FcSliderZSVal
    }))
  }

  const handleFcPSSlider = (val) => {
    setFcSliderPSVal(val)

    dispatch(set_params({
      ...params,
      articlesNum: FcSliderPSVal
    }))
  }

  const getProductGroup = (val) => {
    console.log(val);
    // dispatch(set_params({
    //     ...params,
    //     groupId: val.id
    // }))

    setProductGroupItem(val)
    console.log(productGroupItem,'---');
    setOpenProductGroup(false)
    productRefetch()
  }

  const getProductName = (val) => {
    setProductNameItem(val)
    setOpenProduct(false)
    getProfitModelInfoFun(val.id)

    dispatch(set_params({
      ...params,
      groupId: val.id
    }))
  }

  const getProductYL = (val) => {
    dispatch(set_params({
      ...params,
      profitModelId: val.id
    }))
    setYlItem(val)
    setOpenProductYL(false)
  }

  // useEffect(() => {
  //   handleBigMenu(list[0])
  // }, []);

  const handleProductGroup = () => {
    setGroupSearchText('')
    setOpenProductGroup(true)
    groupRefetch()
  }

  const handleProdut = () => {
    setProductSearchText('')
    setOpenProduct(true)
    productRefetch()
  }

  // @ts-ignore
  return (
      <FcView style={styles.container}>

        <FormTitle style={{paddingHorizontal: 16}} isLeftIcon title='选私有库关联产品'
                   titleHint='选择的产品会关联私有资料库'/>
        <Flex wrap='wrap' style={styles.big_menu}>
          {typeList?.map((item, index) =>
              <FcButton
                  key={index} onClick={() => handleProduct(item)}
                  type={typeId === item.id ? 'txtBK' : 'default'}
                  style={[styles.big_menu_item]}
                  itemStyle={{width: '100%', height: '100%'}}
                  textName={item.name} borderWidth={1}></FcButton>
          )}
        </Flex>

        <View style={{paddingHorizontal: 16}}>
          <FormTitle style={{marginTop: 8}} title='选产品分组'/>
          <TouchableOpacity onPress={() => handleProductGroup(true)}>
            <View style={styles.item_wrap}>
              <Text
                  style={[productGroupItem.name ? styles.item_label : styles.item_hint]}>{productGroupItem.name || '请选择'}</Text>
              <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#79797A'}}>&#xe609;</Text>
            </View>
          </TouchableOpacity>

          <FormTitle style={{marginTop: 8}} title='选产品名称'/>
          <TouchableOpacity onPress={() => handleProdut()}>
            <View style={styles.item_wrap}>
              <Text
                  style={[productNameItem.name ? styles.item_label : styles.item_hint]}>{productNameItem.name || '请选择'}</Text>
              <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#79797A'}}>&#xe609;</Text>
            </View>
          </TouchableOpacity>

          <FormTitle style={{marginTop: 8}} title='选盈利模式'/>
          <TouchableOpacity onPress={() => setOpenProductYL(true)}>
            <View style={styles.item_wrap}>
              <Text style={[ylItem.typeName ? styles.item_label : styles.item_hint]}>{ylItem.typeName || '请选择'}</Text>
              <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#79797A'}}>&#xe609;</Text>
            </View>
          </TouchableOpacity>
        </View>


        <View style={{paddingHorizontal: 16}}>

          <FormTitle title='单篇字数'
                     style={{marginBottom: 8, marginTop: 4}}
                     right={
                       <View style={styles.slider_wrap}>
                         <TextInput style={styles.slider_input} value={FcSliderZSVal + ''}></TextInput>
                         <Text style={styles.slider_txt}>个</Text>
                       </View>
                     }/>
          <FcSlider value={FcSliderZSVal} showMinMax min={100} max={500} onFcSlider={handleFcZSSlider}/>

          <FormTitle title='输出篇数'
                     style={{marginBottom: 8, paddingTop: 32}}
                     right={
                       <View style={styles.slider_wrap}>
                         <TextInput style={styles.slider_input} value={FcSliderPSVal + ''}></TextInput>
                         <Text style={styles.slider_txt}>个</Text>
                       </View>
                     }/>
          <FcSlider value={FcSliderPSVal} min={1} max={10} showMinMax onFcSlider={handleFcPSSlider}/>
        </View>

        <FcModal
            isOpen={openProductGroup}
            onFcModalClose={() => setOpenProductGroup(false)}
            titleText='选择产品分组'
            header={<FcSearch searchText={groupSearchText} onSearch={(val) => setGroupSearchText(val)}/>}
            titleBottomBorderWidth={0}
        >
          <View>
            {groupList.map((item, index) => (
                <TouchableOpacity key={index}
                                  activeOpacity={1}
                                  style={[styles.modal_item_text, pressedIndex === index && styles.modal_item_pressed]}
                                  onPress={() => getProductGroup(item)}
                                  onPressIn={() => setPressedIndex(index)}
                                  onPressOut={() => setPressedIndex(-1)}
                >
                  <Text numberOfLines={1} ellipsizeMode="tail">{item.name}</Text>
                </TouchableOpacity>
            ))}
            {groupList?.length <= 0 &&
                <View style={{
                  flexDirection: 'column',
                  alignItems: 'center',
                  justifyContent: 'center',
                  paddingTop: 60,
                  paddingBottom: 120
                }}>
                  <NoData hintText='暂无分组'/>
                </View>
            }
          </View>
        </FcModal>
        <FcModal
            isOpen={openProduct}
            onFcModalClose={() => setOpenProduct(false)}
            titleText='选择产品名称'
            header={<FcSearch searchText={productSearchText} onSearch={(val) => setProductSearchText(val)}/>}
            titleBottomBorderWidth={0}
        >
          <View>
            {productList.map((item, index) => (
                <TouchableOpacity key={index}
                                  activeOpacity={1}
                                  style={[styles.modal_item_text, pressedIndex === index && styles.modal_item_pressed]}
                                  onPress={() => getProductName(item)}
                                  onPressIn={() => setPressedIndex(index)}
                                  onPressOut={() => setPressedIndex(-1)}
                >
                  <Text numberOfLines={1} ellipsizeMode="tail">{item.name}</Text>
                </TouchableOpacity>
            ))}
            {productList?.length <= 0 &&
                <View style={{
                  flexDirection: 'column',
                  alignItems: 'center',
                  justifyContent: 'center',
                  paddingTop: 60,
                  paddingBottom: 120
                }}>
                  <NoData hintText='暂无产品'/>
                </View>
            }
          </View>
        </FcModal>
        <FcModal
            isOpen={openProductYL}
            onFcModalClose={() => setOpenProductYL(false)}
            titleText='选择盈利模式'
            titleBottomBorderWidth={0}
        >
          <View>
            {ylList.map((item, index) => (
                <TouchableOpacity key={index}
                                  activeOpacity={1}
                                  style={[styles.modal_item_text, pressedIndex === index && styles.modal_item_pressed]}
                                  onPress={() => getProductYL(item)}
                                  onPressIn={() => setPressedIndex(index)}
                                  onPressOut={() => setPressedIndex(-1)}
                >
                  <Text numberOfLines={1} ellipsizeMode="tail">{item.typeName}</Text>
                </TouchableOpacity>
            ))}
            {ylList?.length<=0 &&
                <View style={{flexDirection: 'column',alignItems: 'center',justifyContent: 'center',paddingTop: 30,paddingBottom: 60}}>
                  <NoData hintText='暂无盈利模式资料' />
                  <FcButton
                      onClick={() => router.navigate(`/aiFeeding`)}
                      type='BjJB'
                      colors={['#6989FF','#C65EFD']}
                      style={{width: 144,height: 32,justifyContent: 'center'}}
                      itemStyle={{borderRadius: 8}}
                      textName='去私有化资料新增'></FcButton>
                </View>
            }
          </View>
        </FcModal>
      </FcView>
  )
}

export default UseExplosiveWrap

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'white',
    borderRadius: 8,
    paddingBottom: 16
  },
  big_menu_item: {
    width: 100,
    height: 40,
    lineHeight: 40,
    borderRadius: 8,
    marginHorizontal: 8,
    marginBottom: 8
  },
  input_wrap: {
    flexDirection: 'row',
    alignItems: "center",
    height: 56,
    borderRadius: 10,
    paddingHorizontal: 12,
    backgroundColor: '#F1F2F4',
    marginBottom: 16
  },
  input_label: {
    fontSize: 17,
    color: 'rgba(0,0,0,0.9)',
    flexDirection: 'row',
    alignItems: "center",
    marginRight: 10
  },
  input_val: {
    fontSize: 17,
    color: 'rgba(0,0,0,0.3)',
    flex: 1,
    height: '100%'
  },
  slider_wrap: {
    flexDirection: "row",
    alignItems: "center",
  },
  slider_input: {
    width: 56,
    height: 32,
    textAlign: "center",
    borderRadius: 8,
    backgroundColor: '#F1F2F4'
  },
  slider_txt: {
    marginLeft: 8,
    fontSize: 14,
    color: 'rgba(0,0,0,0.5)'
  },

  item_wrap: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: 'space-between',
    height: 56,
    paddingHorizontal: 12,
    backgroundColor: '#F1F2F4',
    borderRadius: 8
  },
  item_label: {
    fontSize: 17,
    color: 'rgba(0,0,0,0.9)'
  },
  item_hint: {
    fontSize: 17,
    color: 'rgba(0,0,0,0.3)'
  },
  modal_item_text: {
    marginHorizontal: 16,
    height: 56,
    alignItems: 'center',
    justifyContent: 'center',
    borderBottomColor: 'rgba(0,0,0,0.05)',
    borderBottomWidth: 1,
    fontSize: 17,
    color: 'rgba(0,0,0,0.9)'
  },
  modal_item_pressed: {
    backgroundColor: 'rgba(0,0,0,0.05)'
  },
  search_wrap: {
    flexDirection: 'row',
    alignItems: "center",
    backgroundColor: '#F1F2F4',
    borderRadius: 9,
    marginHorizontal: 16,
    height: 40,
    paddingHorizontal: 14
  },
  search: {
    flex: 1,
    height: '100%',
    color: 'rgba(0,0,0,0.9)'
  }
})